package com.goldsign.pay.server.zuul.filter;

import com.alibaba.fastjson.JSON;
//import com.goldsign.pay.common.util.ApiHelpUtil;
//import com.goldsign.pay.common.util.Encodes;
//import com.goldsign.pay.common.util.Md5;
//import com.goldsign.pay.common.util.rsa.SigNatrueUtil;
import com.goldsign.pay.server.zuul.entity.WrapperResponse;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 安全过滤
 * @author johnny
 *
 */
public class SecurityFilter extends ZuulFilter {
	private Logger log = LoggerFactory.getLogger(SecurityFilter.class);
//	pre、routing、post
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}
	
	@Override
	public int filterOrder() {
		return 1;
	}
	
	@Override
	public boolean shouldFilter() {
		return true;
	}
	
	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		try {
		  HttpServletRequest request = ctx.getRequest();
			HttpServletResponse response = ctx.getResponse();
		  log.info("send {} request to {}",request.getMethod() ,  request.getRequestURI().toString());

			if(!validateToken(request,response)) {
//			  ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//		      ctx.set("error.exception", "123");
//		      ctx.set("error.message", "msg123");
				ctx.setResponseStatusCode(401);
				ctx.setResponseBody(JSON.toJSONString(new WrapperResponse(9001, "auth error")));
			}
			//如果用户名和密码都正确，则继续执行下一个filter
			if(validateToken(request,response)){
				ctx.setSendZuulResponse(true);//会进行路由，也就是会调用api服务提供者
				ctx.setResponseStatusCode(200);
//				ctx.set("isOK",true);//可以把一些值放到ctx中，便于后面的filter获取使用
			}else{
				ctx.setSendZuulResponse(false);//不需要进行路由，也就是不会调用api服务提供者
				ctx.setResponseStatusCode(401);
				ctx.set("isOK",false);//可以把一些值放到ctx中，便于后面的filter获取使用
				//返回内容给客户端
				ctx.setResponseBody("{\"result\":\"post auth not correct!\"}");// 返回错误内容
			}
		  
		  return null;
		} catch (Exception e) {
		  String error = "Error during filtering[ErrorFilter]";
		  log.error(error,e);
		  ctx.setResponseBody(JSON.toJSONString(new WrapperResponse(500, error)));
		}
		return null;
	}

	private boolean validateToken(HttpServletRequest req,HttpServletResponse response){
		return false;
		/*String requestURI = req.getRequestURI();
		String[] signFields = null;
		String signField = req.getParameter("signFileds");
		if(StringUtils.isNoneBlank(signField)){
			signFields = signField.split(",");
		}
		try {
			Map parameterMap = req.getParameterMap();
			List<String> plist=new ArrayList<String>();
			for(Object key:parameterMap.keySet()){
				if("signature".equals(key)){
					continue;
				}
				if(signFields!=null && signFields.length > 0){
					if(!Arrays.asList(signFields).contains(key.toString())){
						continue;
					}
				}
				plist.add((String)key);
			}

			Collections.sort(plist);
			StringBuilder sb=new StringBuilder();
			for(int i =0;i<plist.size();i++){
				sb.append(plist.get(i));
				sb.append("=");
				sb.append(req.getParameter(plist.get(i)));
				if(i==plist.size()-1){
					continue;
				}
				sb.append("&");
			}

			String signatrue = req.getParameter("signature");
			String appId = req.getParameter("app_id");
			if(null==signatrue){
				log.info("获取不到签名"+requestURI);
				//SysLog.info("给予通过");
				//return true;
				System.out.println("【##########获取不到签名##########】");
				ApiHelpUtil.writeNoSig(response);
				return false;

			}
			signatrue= Encodes.urlDecode(signatrue);
			String plainText = Md5.md5_32(sb.toString());
			if (!SigNatrueUtil.authSigtrueByPrivateKey(plainText, signatrue,"")) {
				System.out.println("【##########签名错误##########】");
				ApiHelpUtil.writeNoSig(response);
				return false;
			}
			return true;
		} catch (Exception e) {

			System.out.println("【##########获取不到签名，下二个方法##########】");
			ApiHelpUtil.writeNoSig(response);
			return false;
		}*/
	}
}
